package com.ibangnuo.manage.service.newLandpay;

import com.alibaba.fastjson.JSONObject;
import com.ibangnuo.framework.domain.CommercialTenant;
import com.ibangnuo.framework.domain.Order;
import com.ibangnuo.framework.domain.OrderDetails;
import com.ibangnuo.framework.domain.Pay;
import com.ibangnuo.framework.domain.request.newLandpay.NewLandPayRequest;
import com.ibangnuo.framework.domain.response.alipay.PayCode;
import com.ibangnuo.framework.model.response.ObjectResult;
import com.ibangnuo.framework.newLandpay.api.NewLandpayClient;
import com.ibangnuo.framework.newLandpay.impl.client.DefaultNewLandpayClient;
import com.ibangnuo.framework.newLandpay.impl.request.AliServicePayRequest;
import com.ibangnuo.framework.newLandpay.impl.response.AliServicePayResponse;
import com.ibangnuo.framework.utils.PrimaryKeyUtil;
import com.ibangnuo.manage.dao.OrderDetailsRepository;
import com.ibangnuo.manage.dao.OrderRepository;
import com.ibangnuo.manage.dao.alipay.PayRepository;
import com.ibangnuo.manage.dao.employee.CommercialRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: wwy
 * @Date: 2020-01-09 14:34
 */
@Service
public class NewLandPayService {
    private static Logger LOGGER = LoggerFactory.getLogger(NewLandPayService.class);
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private PayRepository payRepository;
    @Autowired
    private CommercialRepository commercialRepository;
    @Autowired
    private OrderDetailsRepository orderDetailsRepository;

    private String key = "9FF13E7726C4DFEB3BED750779F59711";
    /**
     * 新大陆支付
     * 1.入订单表，状态为未支付
     * 2.订单详情表
     * 2.入支付表
     * @param newLandPayRequest
     * @return
     */
    public ObjectResult pay(NewLandPayRequest newLandPayRequest){
        Order order = new Order();
        CommercialTenant commercialTenant = commercialRepository.findByPId(newLandPayRequest.getPId());
        if(commercialTenant !=null){
            order.setCommercialTenantId(commercialTenant.getId());//所属商户
        }
        order.setStatus(0);
        order.setPayType("F");
        order.setSn(newLandPayRequest.getSn());
        order.setActualPayment(Integer.parseInt(new DecimalFormat("0").format(newLandPayRequest.getTotalAmount()*100)));
        order.setCreateTime(new Date());
        Order save = orderRepository.save(order);
        AliServicePayResponse response = this.aliServicePayResult(newLandPayRequest);
        Pay pay = new Pay();
        pay.setCreateTime(new Date());
        pay.setOrderId(save.getId());
        if(response != null){
            if(response.isSuccess() && "000000".equals(response.code())){
                save.setStatus(1);
                save.setOutTradeNo(response.getTradeNo());
                save.setSerialNumber(response.getLogNo());
                OrderDetails orderDetails = new OrderDetails();
                orderDetails.setOrderId(save.getId());
                orderDetails.setContent(JSONObject.toJSONString(response));
                orderDetails.setCreateTime(new Date());
                pay.setMoney(Integer.parseInt(new DecimalFormat("0").format(newLandPayRequest.getTotalAmount()*100)));
                pay.setDescribe("支付成功");
                pay.setStatus(1);
                orderRepository.save(order);
                payRepository.save(pay);
                orderDetailsRepository.save(orderDetails);
                return new ObjectResult(PayCode.PAY_SUCCESS,null);
            }else{
                save.setStatus(2);
                save.setOutTradeNo(response.getTradeNo());
                save.setSerialNumber(response.getLogNo());
                pay.setMoney(Integer.parseInt(new DecimalFormat("0").format(newLandPayRequest.getTotalAmount()*100)));
                pay.setDescribe("支付失败");
                pay.setStatus(0);
            }
        }else{
            save.setStatus(2);
            pay.setMoney(Integer.parseInt(new DecimalFormat("0").format(newLandPayRequest.getTotalAmount()*100)));
            pay.setDescribe("支付失败");
            pay.setStatus(0);
        }
        orderRepository.save(order);
        payRepository.save(pay);
        return new ObjectResult(PayCode.PAY_FILL,null);
    }

    /**
     * 新大陆支付宝服务窗接口调用
     * @param newLandPayRequest
     * @return
     */
    private AliServicePayResponse aliServicePayResult(NewLandPayRequest newLandPayRequest){
        NewLandpayClient newLandpayClient = new DefaultNewLandpayClient(key);
        AliServicePayRequest request = new AliServicePayRequest();

        Map<String,String> preMap = new HashMap<>();
        preMap.put("orgNo","11658");//机构号
        preMap.put("mercId","800290000007906");//商户号
        preMap.put("trmNo", "XB006439");//设备号
        preMap.put("ali_user_id",newLandPayRequest.getAliUserId());
        preMap.put("aliuser_no",newLandPayRequest.getAliuserNo());
        preMap.put("signType","MD5");
        preMap.put("subject",newLandPayRequest.getSubject());
        preMap.put("tradeNo",PrimaryKeyUtil.nextId()+"");
        preMap.put("txnTime",System.currentTimeMillis()+"");
        preMap.put("version","V1.0.0");
        preMap.put("amount",new DecimalFormat("0").format(newLandPayRequest.getAmount()*100));
        preMap.put("total_amount",new DecimalFormat("0").format(newLandPayRequest.getTotalAmount()*100));
        request.setPre(preMap);
        AliServicePayResponse response = newLandpayClient.execute(request);
        return response;
    }
}
